package com.huatai.verity.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.common.error.exception.SecureException;
import com.huatai.common.error.exception.ServiceException;
import com.huatai.common.util.AuthUtil;
import com.huatai.common.util.ObjectUtil;
import com.huatai.verity.entity.AuthManage;
import com.huatai.verity.mapper.AuthManageMapper;
import com.huatai.verity.service.AuthManageService;
import com.huatai.verity.utils.AESUtils;
import com.huatai.verity.utils.DateUtils;
import com.huatai.verity.vo.AuthManageParmVo;
import com.huatai.verity.vo.SignCodeVo;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;


/**
 * @program: ht-system
 * @description: 授权码接口
 * @author: songxiude
 * @create: 2023-07-25 09:13
 **/
@Service
@Slf4j
public class AuthManageServiceImpl extends ServiceImpl<AuthManageMapper, AuthManage> implements AuthManageService {
	/**
	 * 新增更新授权码
	 *
	 * @param authManage
	 * @return
	 */
	public boolean saveUpdate(AuthManage authManage) {
		//如果id不传视为新增
		if (ObjectUtil.isEmpty(authManage.getId()) || authManage.getId().longValue() <= 0) {
			authManage.setId(IdWorker.getId());
			authManage.setCreateUser(AuthUtil.getUser().getAccount());
		}
		authManage.setUpdateUser(AuthUtil.getUser().getAccount());
		return saveOrUpdate(authManage);
	}

	/**
	 * 获取授权码列表
	 *
	 * @param authManageParmVo
	 * @return
	 */
	public IPage<Object> getAuthManageList(AuthManageParmVo authManageParmVo) {
		long p = authManageParmVo.getPage() > 0 ? authManageParmVo.getPage() : 1;
		long size = authManageParmVo.getSize() > 0 ? authManageParmVo.getSize() : 10;
		Page<Object> page = Page.of(p, size);
//		LambdaQueryWrapper<Object> queryWrapper = new LambdaQueryWrapper<>();

		return baseMapper.getAuthManageList(page, authManageParmVo);
	}

	/**
	 * 获取授权码
	 *
	 * @param signCodeVo
	 * @return
	 */
	public Map<String, String> getSignCode(SignCodeVo signCodeVo) {

		Map<String, String> license = AESUtils.getLicense(signCodeVo.getSystemCode(), signCodeVo.getAuthStartTime(), signCodeVo.getAuthEndTime(), signCodeVo.getAuthStartTime(), "waytale_202307");
		if (ObjectUtil.isEmpty(license)) {
			throw new ServiceException("获取授权签名失败，请检查系统签名是否正确!");
		}
		return license;
	}

	/**
	 * 导出签名证书xml
	 *
	 * @param id
	 * @param response
	 */
	public void exportSignXml(Long id, HttpServletResponse response) {
		AuthManage authManage = getById(id);
		Assert.isTrue(ObjectUtil.isNotEmpty(authManage), "该授权证书不存在");
		try {
			//生成licence文件
			Document document = DocumentHelper.createDocument();
			//根节点
			Element rootEle = document.addElement("license");
			//功能数据节点,扩展参数时可在此节点下扩展
			Element dataEle = rootEle.addElement("features");
			Element featureEle = dataEle.addElement("feature");
			featureEle.addAttribute("name", "lastValidateTi");
			featureEle.addAttribute("ti", authManage.getTi());
			//签名节点
			Element signEle = rootEle.addElement("signature");
			signEle.setText(authManage.getAuthCode());

			String xml = document.asXML();

			//导出

			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename=" + "license.xml");
			response.setContentType("application/octet-stream");
			response.setCharacterEncoding("UTF-8");
			OutputStream outputStream = response.getOutputStream();
			byte[] licenseBytes = xml.getBytes();
			// 输出文件
			outputStream.write(licenseBytes);

			outputStream.close();
		} catch (Exception e) {
			log.error("导出证书失败");
		}

	}

	public void exportSignXmlbk(Long id, String path) {
		AuthManage authManage = getById(id);
		Assert.isTrue(ObjectUtil.isNotEmpty(authManage), "该授权证书不存在");
		try {
			//生成licence文件
			Document document = DocumentHelper.createDocument();
			//根节点
			Element rootEle = document.addElement("license");
			//功能数据节点,扩展参数时可在此节点下扩展
			Element dataEle = rootEle.addElement("features");
			Element featureEle = dataEle.addElement("feature");
			featureEle.addAttribute("name", "lastValidateTi");
			featureEle.addAttribute("ti", authManage.getTi());
			//签名节点
			Element signEle = rootEle.addElement("signature");
			signEle.setText(authManage.getAuthCode());

			OutputFormat format = OutputFormat.createPrettyPrint();
			// 设置编码格式
			format.setEncoding("UTF-8");
			FileWriter fileWriter = new FileWriter(new File(path));
			XMLWriter xmlWriter = new XMLWriter(fileWriter, format);
			// 设置是否转义，默认使用转义字符
			xmlWriter.setEscapeText(false);
			xmlWriter.write(document);
			xmlWriter.close();
		} catch (Exception e) {
			log.error("导出证书失败");
			log.error(e.getMessage());
		}

	}
}
